#!/bin/bash
# set -e

TOPDIR=`readlink -f $0`
TOPDIR_FILE_NAME=`basename $TOPDIR`
TOPDIR=`dirname $TOPDIR`

# check parament num
if [ $# -ne 6 ]; then
	echo "code_post excute failed! reason: error parament"
	echo "usage:"
	echo "$TOPDIR_FILE_NAME target_name target_path project_path version_file output_name crc_need_flag"
	exit -1
fi

TARGET_NAME=`echo "$1"`
TARGET_PATH=`echo "$2" | tr '\\' '%' | sed "s/%/\//g"`
TARGET_PATH_WIN=`echo "$2"`
PROJECT_PATH=`echo "$3" | tr '\\' '%' | sed "s/%/\//g"`
PROJECT_PATH_WIN=`echo "$3"`
VERSION_FILE=`echo "$4" | tr '\\' '%' | sed "s/%/\//g"`
OUTPUT_NAME=`echo "$5"`
CRC_NEED_FLAG=`echo "$6"`
MIDDLE_OUTPUT_NAME='load'

echo TOPDIR=$TOPDIR
echo TARGET_NAME=$TARGET_NAME
echo TARGET_PATH=$TARGET_PATH
echo TARGET_PATH_WIN=$TARGET_PATH_WIN
echo PROJECT_PATH=$PROJECT_PATH
echo PROJECT_PATH_WIN=$PROJECT_PATH_WIN
echo VERSION_FILE=$VERSION_FILE
echo OUTPUT_NAME=$OUTPUT_NAME
echo MIDDLE_OUTPUT_NAME=$MIDDLE_OUTPUT_NAME

if [ ! -f $VERSION_FILE ]; then
	echo "code_post excute failed! reason: version_file not exist"
	exit 5
fi

version=`grep "WL_SW_VERSION" $VERSION_FILE | awk '{print $3}'`
version_str=`echo ${version:2:1}.${version:3:1}.${version:4:1}.${version:5:1}`
echo version=$version
echo version_str=$version_str

files=$(ls $PROJECT_PATH/../bin/*.hex 2> /dev/null | wc -l)
if [ "$files" != "0" ];then
	rm $PROJECT_PATH/../bin/*.hex
fi

files=$(ls $PROJECT_PATH/../bin/*.bin 2> /dev/null | wc -l)
if [ "$files" != "0" ];then
	rm $PROJECT_PATH/../bin/*.bin
fi

if [ ! -d $PROJECT_PATH/../bin ];then
	mkdir $PROJECT_PATH/../bin
fi

if [ $CRC_NEED_FLAG -eq 1 ];then
	cmd /c $TOPDIR/safe_tools/crc_gen_keil.bat $TARGET_NAME $TARGET_PATH_WIN $PROJECT_PATH_WIN $MIDDLE_OUTPUT_NAME
	if [ $? -ne 0 ]; then
		echo "code_post excute failed! reason: crc_gen_keil.bat"
		exit 5
	fi
	cmd /c $TOPDIR/safe_tools/hex2bin_tool/hex2bin.exe -e .bin $PROJECT_PATH/../bin/$MIDDLE_OUTPUT_NAME.hex
	if [ $? -ne 0 ]; then
		echo "code_post excute failed! reason: hex2bin"
		exit 5
	fi
elif [ $CRC_NEED_FLAG -eq 2 ];then
	cmd /c $TOPDIR/safe_tools/vcu_gen_crc.bat $TARGET_NAME $TARGET_PATH_WIN $PROJECT_PATH_WIN $MIDDLE_OUTPUT_NAME
	if [ $? -ne 0 ]; then
		echo "code_post excute failed! reason: crc_gen_keil.bat"
		exit 5
	fi
	cmd /c $TOPDIR/safe_tools/hex2bin_tool/hex2bin.exe -e .bin $PROJECT_PATH/../bin/$MIDDLE_OUTPUT_NAME.hex
	if [ $? -ne 0 ]; then
		echo "code_post excute failed! reason: hex2bin"
		exit 5
	fi
else
	echo "crc inject skip!"
	cp $PROJECT_PATH$TARGET_PATH$TARGET_NAME.hex $PROJECT_PATH/../bin/$MIDDLE_OUTPUT_NAME.hex
	cp $PROJECT_PATH$TARGET_PATH$TARGET_NAME.bin $PROJECT_PATH/../bin/$MIDDLE_OUTPUT_NAME.bin
fi

cp $PROJECT_PATH/../bin/$MIDDLE_OUTPUT_NAME.hex $PROJECT_PATH/../bin/$OUTPUT_NAME$version_str.hex
cp $PROJECT_PATH/../bin/$MIDDLE_OUTPUT_NAME.bin $PROJECT_PATH/../bin/$OUTPUT_NAME$version_str.bin

#sleep 2
echo "code_post excute success!"
exit 0